<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>在线客服 - 购物商城</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        .chat-container {
            height: 500px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 15px;
            background: linear-gradient(to bottom, #f8f9fa, #ffffff);
            position: relative;
        }
        
        .message-group {
            margin-bottom: 20px;
        }
        
        .time-divider {
            text-align: center;
            margin: 15px 0;
            position: relative;
        }
        
        .time-divider::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: #e0e0e0;
            z-index: 1;
        }
        
        .time-text {
            background: #ffffff;
            padding: 5px 15px;
            border-radius: 12px;
            font-size: 12px;
            color: #999;
            position: relative;
            z-index: 2;
            display: inline-block;
            border: 1px solid #e0e0e0;
        }
        
        .message-item {
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;
        }
        
        .message-item.customer {
            flex-direction: row-reverse;
        }
        
        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: white;
            flex-shrink: 0;
            margin: 0 10px;
        }
        
        .avatar.customer {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .avatar.service {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        .message-content {
            max-width: 60%;
            position: relative;
        }
        
        .message-bubble {
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
            position: relative;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .message-item.customer .message-bubble {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .message-item.service .message-bubble {
            background: #ffffff;
            color: #333;
            border: 1px solid #e0e0e0;
            border-bottom-left-radius: 5px;
        }
        
        .sender-name {
            font-size: 11px;
            color: #999;
            margin-bottom: 5px;
            padding: 0 5px;
        }
        
        .message-item.customer .sender-name {
            text-align: right;
        }
        
        .service-selector {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .service-card {
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }
        
        .service-card:hover {
            border-color: #007bff;
            box-shadow: 0 2px 10px rgba(0,123,255,0.1);
            transform: translateY(-2px);
        }
        
        .service-card.selected {
            border-color: #007bff;
            background: #f0f8ff;
        }
        
        .service-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
            margin-right: 15px;
        }
        
        .current-service-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }
        
        .input-area {
            border-top: 1px solid #e0e0e0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 0 0 10px 10px;
        }
        
        .chat-input {
            border: 1px solid #e0e0e0;
            border-radius: 20px;
            padding: 10px 20px;
            resize: none;
            outline: none;
            box-shadow: none;
        }
        
        .chat-input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
        }
        
        .send-btn {
            border-radius: 20px;
            padding: 10px 25px;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px 20px;
            color: #999;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #ddd;
        }
    </style>
</head>
<body data-user-role="customer">
<!-- 导航栏 -->
<div th:replace="~{common/navbar :: navbar}"></div>

<!-- 引入增强版全局通知组件 -->
<div th:replace="~{common/enhanced-global-notification :: notification}"></div>

<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <h1 class="mb-4">
                <i class="bi bi-headset text-primary"></i> 在线客服
                <small class="text-muted">- 专业服务，贴心支持</small>
            </h1>
        </div>
    </div>

    <!-- 错误信息 -->
    <div th:if="${error}" class="alert alert-danger" role="alert">
        <i class="bi bi-exclamation-triangle"></i> <span th:text="${error}">错误信息</span>
    </div>

    <div class="row">
        <div class="col-md-8">
            <!-- 当前对话信息 -->
            <div th:if="${hasConversation}" class="current-service-info">
                <div class="service-avatar me-3">
                    <i class="bi bi-person"></i>
                </div>
                <div>
                    <h6 class="mb-1">正在与客服对话</h6>
                    <p class="mb-0" th:text="'客服：' + ${currentService.userName}">客服：客服姓名</p>
                </div>
                <div class="ms-auto">
                    <span class="badge bg-success">对话中</span>
                </div>
            </div>

            <!-- 聊天区域 -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0"><i class="bi bi-chat-dots"></i> 对话记录</h6>
                    <span class="badge bg-success" th:if="${hasConversation}">在线</span>
                    <span class="badge bg-secondary" th:unless="${hasConversation}">未连接</span>
                </div>
                <div class="card-body p-0">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">
                            <i class="bi bi-chat-dots"></i> 
                            <span th:if="${hasConversation}">与 <span th:text="${currentService.userName}">客服</span> 的对话</span>
                            <span th:unless="${hasConversation}">选择客服开始对话</span>
                        </h5>
                        <div th:if="${hasConversation}">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="closeConversation()">
                                <i class="bi bi-x-circle"></i> 结束对话
                            </button>
                        </div>
                    </div>
                    <div class="chat-container" id="chatContainer">
                        <!-- 空状态 -->
                        <div th:if="${#lists.isEmpty(messages)}" class="empty-state">
                            <i class="bi bi-chat-dots"></i>
                            <h5>暂无对话记录</h5>
                            <p th:if="${!hasConversation}">请先选择客服开始对话</p>
                            <p th:if="${hasConversation}">开始与客服的对话吧！</p>
                        </div>
                        
                        <!-- 消息列表 -->
                        <div th:if="${!#lists.isEmpty(messages)}">
                            <div th:each="message, iterStat : ${messages}">
                                <!-- 时间分隔线 -->
                                <div th:if="${iterStat.first or messages[iterStat.index - 1].createTime != message.createTime}" 
                                     class="time-divider">
                                    <span class="time-text" th:text="${message.createTime}">时间</span>
                                </div>
                                
                                <!-- 消息项 -->
                                <div th:class="${message.isFromCustomer} ? 'message-item customer' : 'message-item service'">
                                    <div th:class="${message.isFromCustomer} ? 'avatar customer' : 'avatar service'">
                                        <i th:class="${message.isFromCustomer} ? 'bi bi-person' : 'bi bi-headset'"></i>
                                    </div>
                                    <div class="message-content">
                                        <div class="sender-name" th:text="${message.senderName}">发送者</div>
                                        <div class="message-bubble" th:text="${message.content}">消息内容</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 输入区域 -->
                <div class="input-area" th:if="${hasConversation}">
                    <form id="messageForm" class="d-flex">
                        <div class="flex-grow-1 me-2">
                            <textarea id="messageInput" class="form-control chat-input" rows="2" 
                                      placeholder="输入您的消息..." required></textarea>
                        </div>
                        <div class="align-self-end">
                            <button type="submit" class="btn btn-primary send-btn" id="sendButton">
                                <i class="bi bi-send"></i> 发送
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 客服选择区域 -->
        <div class="col-md-4">
            <div class="service-selector" th:if="${!hasConversation}">
                <h6 class="mb-3"><i class="bi bi-people"></i> 选择客服</h6>
                
                <!-- 检查是否有客服数据 -->
                <div th:if="${#lists.isEmpty(customerServices)}" class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle"></i> 暂无可用客服，请稍后再试
                </div>
                
                <div th:each="service : ${customerServices}" 
                     class="service-card" 
                     th:data-service-id="${service.userID}"
                     th:data-service-name="${service.userName}">
                    <div class="d-flex align-items-center">
                        <div class="service-avatar">
                            <i class="bi bi-headset"></i>
                        </div>
                        <div>
                            <h6 class="mb-1" th:text="${service.userName}">客服姓名</h6>
                            <p class="mb-0 text-muted small">专业客服，在线服务</p>
                            <small class="text-muted">ID: <span th:text="${service.userID}">ID</span></small>
                        </div>
                        <div class="ms-auto">
                            <span class="badge bg-success">在线</span>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-3">
                    <button id="startChatBtn" class="btn btn-primary" disabled onclick="startConversation()">
                        <i class="bi bi-chat-left-text"></i> 开始对话
                    </button>
                </div>
            </div>
            
            <!-- 客服信息卡片 -->
            <div class="card" th:if="${hasConversation}">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-person-badge"></i> 客服信息</h6>
                </div>
                <div class="card-body text-center">
                    <div class="service-avatar mx-auto mb-3">
                        <i class="bi bi-headset"></i>
                    </div>
                    <h6 th:text="${currentService.userName}">客服姓名</h6>
                    <p class="text-muted small">专业客服，为您提供优质服务</p>
                    <span class="badge bg-success">在线服务中</span>
                </div>
            </div>
            
            <!-- 服务指南 -->
            <div class="card mt-3">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-info-circle"></i> 服务指南</h6>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled small">
                        <li class="mb-2"><i class="bi bi-check-circle text-success"></i> 选择合适的客服开始对话</li>
                        <li class="mb-2"><i class="bi bi-check-circle text-success"></i> 详细描述您的问题</li>
                        <li class="mb-2"><i class="bi bi-check-circle text-success"></i> 耐心等待客服回复</li>
                        <li class="mb-2"><i class="bi bi-check-circle text-success"></i> 问题解决后可结束对话</li>
                    </ul>
                    
                    <div class="alert alert-info small mt-3">
                        <i class="bi bi-lightbulb"></i> 
                        <strong>提示：</strong>开始新对话会自动结束当前对话
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let selectedServiceId = null;
    let selectedServiceName = null;
    let messagePollingInterval = null;
    let lastMessageCount = 0;
    
    document.addEventListener('DOMContentLoaded', function() {
        const messageForm = document.getElementById('messageForm');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const chatContainer = document.getElementById('chatContainer');
        
        // 滚动到底部
        if (chatContainer) {
            scrollToBottom();
        }
        
        // 处理表单提交
        if (messageForm) {
            messageForm.addEventListener('submit', function(e) {
                e.preventDefault();
                sendMessage();
            });
        }
        
        // 支持Ctrl+Enter发送
        if (messageInput) {
            messageInput.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'Enter') {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // 自动聚焦到输入框
            messageInput.focus();
        }
        
        // 添加客服卡片点击事件监听器
        document.querySelectorAll('.service-card').forEach(card => {
            card.addEventListener('click', function() {
                const serviceId = this.getAttribute('data-service-id');
                const serviceName = this.getAttribute('data-service-name');
                selectService(this, serviceId, serviceName);
            });
        });
        
        // 如果有活跃对话，开始轮询消息
        if (document.querySelector('.current-service-info')) {
            startMessagePolling();
            // 立即标记消息为已读
            markMessagesAsRead();
        }
        
        // 页面离开时停止轮询
        window.addEventListener('beforeunload', function() {
            stopMessagePolling();
        });
    });
    
    function selectService(element, serviceId, serviceName) {
        // 移除之前的选中状态
        document.querySelectorAll('.service-card').forEach(card => {
            card.classList.remove('selected');
        });
        
        // 添加选中状态
        element.classList.add('selected');
        
        selectedServiceId = serviceId;
        selectedServiceName = serviceName;
        
        // 启用开始对话按钮
        document.getElementById('startChatBtn').disabled = false;
        
        console.log('选择了客服:', serviceId, serviceName);
    }
    
    function startConversation() {
        if (!selectedServiceId) {
            alert('请先选择客服');
            return;
        }
        
        const startBtn = document.getElementById('startChatBtn');
        startBtn.disabled = true;
        startBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 连接中...';
        
        fetch('/customer/start-conversation', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                customerServiceId: selectedServiceId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 刷新页面显示对话界面
                location.reload();
            } else {
                alert('连接失败: ' + data.message);
                startBtn.disabled = false;
                startBtn.innerHTML = '<i class="bi bi-chat-left-text"></i> 开始对话';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('连接失败，请重试');
            startBtn.disabled = false;
            startBtn.innerHTML = '<i class="bi bi-chat-left-text"></i> 开始对话';
        });
    }
    
    function startMessagePolling() {
        // 每2秒检查一次新消息，更加实时
        messagePollingInterval = setInterval(function() {
            fetchMessages();
        }, 2000);
        
        // 立即获取一次消息
        fetchMessages();
        console.log('开始轮询客服消息');
    }
    
    function stopMessagePolling() {
        if (messagePollingInterval) {
            clearInterval(messagePollingInterval);
            messagePollingInterval = null;
        }
    }
    
    function fetchMessages() {
        fetch('/customer/get-messages')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.hasConversation) {
                updateChatContainer(data.messages);
            }
        })
        .catch(error => {
            console.error('获取消息失败:', error);
        });
    }
    
    function updateChatContainer(messages) {
        if (!messages || messages.length === 0) {
            // 如果没有消息，显示空状态
            const chatContainer = document.getElementById('chatContainer');
            if (chatContainer) {
                chatContainer.innerHTML = `
                    <div class="empty-state">
                        <i class="bi bi-chat-dots"></i>
                        <h5>暂无对话记录</h5>
                        <p>开始与客服的对话吧！</p>
                    </div>
                `;
            }
            return;
        }
        
        // 检查是否有新消息
        const hasNewMessages = messages.length > lastMessageCount;
        lastMessageCount = messages.length;
        
        const chatContainer = document.getElementById('chatContainer');
        if (!chatContainer) return;
        
        // 清空现有消息
        chatContainer.innerHTML = '';
        
        // 重新渲染所有消息
        let lastTime = null;
        messages.forEach((message, index) => {
            // 添加时间分隔线
            if (!lastTime || lastTime !== message.createTime) {
                const timeDiv = document.createElement('div');
                timeDiv.className = 'time-divider';
                timeDiv.innerHTML = `<span class="time-text">${message.createTime}</span>`;
                chatContainer.appendChild(timeDiv);
                lastTime = message.createTime;
            }
            
            // 添加消息
            const messageDiv = document.createElement('div');
            messageDiv.className = message.isFromCustomer ? 'message-item customer' : 'message-item service';
            
            messageDiv.innerHTML = `
                <div class="${message.isFromCustomer ? 'avatar customer' : 'avatar service'}">
                    <i class="${message.isFromCustomer ? 'bi bi-person' : 'bi bi-headset'}"></i>
                </div>
                <div class="message-content">
                    <div class="sender-name">${message.senderName}</div>
                    <div class="message-bubble">${message.content}</div>
                </div>
            `;
            
            chatContainer.appendChild(messageDiv);
        });
        
        // 滚动到底部
        scrollToBottom();
        
        // 如果有新消息，检查是否为客服回复
        if (hasNewMessages) {
            // 检查最新消息是否来自客服
            const latestMessage = messages[messages.length - 1];
            if (latestMessage && !latestMessage.isFromCustomer) {
                showNewMessageNotification();
            }
            // 标记消息为已读
            markMessagesAsRead();
        }
    }
    
    function showNewMessageNotification() {
        // 创建新消息通知
        const notification = document.createElement('div');
        notification.className = 'alert alert-info alert-dismissible fade show position-fixed';
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        notification.innerHTML = `
            <i class="bi bi-chat-left-text"></i>
            <strong>新消息</strong>
            <p class="mb-0">客服回复了您的消息</p>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(notification);
        
        // 3秒后自动移除通知
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }
    
    function markMessagesAsRead() {
        fetch('/customer/mark-messages-read', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .catch(error => {
            console.error('标记已读失败:', error);
        });
    }
    
    function sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const message = messageInput.value.trim();
        
        if (!message) {
            return;
        }
        
        // 禁用发送按钮
        sendButton.disabled = true;
        sendButton.innerHTML = '<i class="bi bi-hourglass-split"></i> 发送中...';
        
        // 发送消息
        fetch('/customer/send-to-customer-service', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清空输入框
                messageInput.value = '';
                // 如果返回了消息列表，直接更新界面
                if (data.messages) {
                    updateChatContainer(data.messages);
                } else {
                    // 否则立即获取最新消息
                    fetchMessages();
                }
            } else {
                alert('发送失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('发送失败，请重试');
        })
        .finally(() => {
            // 恢复发送按钮
            sendButton.disabled = false;
            sendButton.innerHTML = '<i class="bi bi-send"></i> 发送';
        });
    }
    
    function endConversation() {
        if (confirm('确定要结束当前对话吗？对话记录将被清除。')) {
            // 这里可以添加结束对话的逻辑
            // 目前简单刷新页面
            location.reload();
        }
    }
    
    function scrollToBottom() {
        const chatContainer = document.getElementById('chatContainer');
        if (chatContainer) {
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    }
    
    function closeConversation() {
        if (confirm('确定要结束当前对话吗？对话记录将被保留。')) {
            fetch('/customer/close-conversation', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('对话已结束');
                    location.reload();
                } else {
                    alert('结束对话失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('结束对话失败:', error);
                alert('结束对话失败，请重试');
            });
        }
    }
</script>
</body>
</html> 